import { reactive, toRefs, getCurrentInstance, h } from "vue"
// ant design
import { message } from "ant-design-vue"
// api
import { literaturelists, literaturedelete, literaturestatus } from "@/api/index"

export function useLiterature() {
    // proxy
    const { proxy } = getCurrentInstance()
    // state
    const state = reactive({
        dataList: [],
    })

    /**
     * 获取列表
     */
    const useGetLiteratureList = (params) => {
        return new Promise((resolve, reject) => {
            literaturelists(params).then(res => {
                state.dataList = res?.content?.data
                resolve(res)
            })
        })
    }

    /**
     * 删除
     */
    const useDeleteLiterature = (row) => {
        proxy.$confirm({
            title: "确认删除？",
            content: "是否确认删除该文献类型",
            okAsync: () => {
              return new Promise((resolve, reject) => { // then，catch
                literaturedelete({literature_id: row.literature_id}).then(() => {
                  message.success('删除成功')
                  useGetLiteratureList()
                  resolve()
                }).catch(() => {
                  reject()
                })
              })
            }
          })
    }

    /**
     * 更新状态
     */
    const useStatusLiterature = (params) => {
        return new Promise((resolveSwitch, rejectSwitch) => {
            proxy.$confirm({
                title: params.status ? "确认禁用？" : "确认启用？",
                content: "是否确定更新文献状态",
                okAsync: () => {
                    return new Promise((resolve, reject) => { // then，catch
                    const req = {
                        literature_id: params.literature_id,
                        literature_status: params.literature_status ? 0 : 1
                    }
                    literaturestatus(req).then((res) => {
                        message.success(res?.msg)
                        resolve()
                        resolveSwitch()
                    }).catch(() => {
                        reject()
                    })
                })
            },
            cancelAsync: () => {
                rejectSwitch()
            }
            })
        })
    }

    return {
        ...toRefs(state),
        useGetLiteratureList,
        useDeleteLiterature,
        useStatusLiterature
    }
}